package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;
    //新增地址
    @Override
    public void addAddress(AddressBook addressBook) {
        //设置当前用户的UserId
        addressBook.setUserId(BaseContext.getCurrentId());
        //设置当前地址的默认地址为0
        addressBook.setIsDefault(0);
        addressBookMapper.insertAddress(addressBook);
    }

    @Override
    public List<AddressBook> queryList() {
        //根据登录用户的id,查询当前用户下的所有的地址
        Long userId = BaseContext.getCurrentId();
        List<AddressBook> addressBookList = addressBookMapper.queryList(userId);
        return addressBookList;
    }

    @Override
    public AddressBook getDefault() {
        //根据用户当前的id,进行查询当前用户的默认地址
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook = addressBookMapper.queryDefault(userId);
        return addressBook;
    }

    @Override
    public void updateAddress(AddressBook addressBook) {
        //根据当前用户的user_Id和地址的Id,进行更新地址的信息
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateAddress(addressBook);
    }

    @Override
    public void deleteAddress(Long id) {
        //根据地址的id进行删除地址
        addressBookMapper.deleteAddress(id);
    }

    @Override
    public AddressBook getAddressById(Long id) {
        //根据地址的id进行查询地址的信息
        AddressBook addressBook = addressBookMapper.getAddressById(id);
        return addressBook;
    }

    @Override
    public void setDefault(AddressBook addressBook) {
       //先将当前用户的所有地址的is_default字段设置为0
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateIsDefaultByUserId(addressBook);
        //再将当前地址的is_default字段设置为1
        addressBook.setIsDefault(1);
        addressBookMapper.updateAddress(addressBook);
    }
}
